package com.ruoyi.douyin.service.imp;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.ConstantDouYinBase;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.vo.AuthVo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.AjaxUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.douyin.service.VideoService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.vo.DouyinVideoListVo;
import com.ruoyi.system.domain.DouyinVideo;
import com.ruoyi.system.service.DouyinVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class VideoServiceImp implements VideoService {
    @Autowired
    private AjaxUtils ajaxUtils;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private DouyinVideoService douyinVideoService;

    /**
     * 视频播放的列表
     *
     * @return
     */
    @Override
    @Cacheable(value = "douyin:video:user:list", key = "#p0[0].openId +':'+#p0[0].cursor")
    public AjaxResult videoList(List<DouyinVideoListVo> douyinVideoListVoList) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<DouyinVideoListVo> collect = douyinVideoListVoList.stream()
                .peek(item -> item
                        .setUserId(loginUser.getUser().getUserId().toString())
                        .setNickname(loginUser.getUser().getNickName())
                        .setAvatar(loginUser.getUser().getAvatar())
                )
                .collect(Collectors.toList());
        for (DouyinVideoListVo douyinVideoListVo : collect) {
            String openId = douyinVideoListVo.getOpenId();
            AuthVo authVo = redisCache.getCacheObject(openId);
            String url = ConstantDouYinBase.Url.BASE_URL.getUrl() + ConstantDouYinBase.Url.USER_VIDEO_LIST.getUrl();
            Map<String, Object> param = new HashMap<>();
            param.put("open_id", openId);
            param.put("cursor", douyinVideoListVo.getCursor());
            param.put("access_token", authVo.getAccessToken());
            param.put("count", 8);
            try {
                return ajaxUtils.doGetWithParams(url, param);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success("success", null);
    }

    /**
     * 获取指定视频详情
     *
     * @return
     */
    @Override
    public AjaxResult videoDetail(List<String> itemIds, String openId) {
        if (openId == null) return AjaxResult.error("未授权");
        AuthVo authVo = redisCache.getCacheObject(openId);
        if (authVo == null) {
            return AjaxResult.error("授权过期");
        }
        String url = ConstantDouYinBase.Url.BASE_URL.getUrl() + ConstantDouYinBase.Url.USER_VIDEO_DETAIL.getUrl();
        try {
            JSONObject body = new JSONObject();
            if (itemIds.size() != 0) body.put("item_ids", JSONArray.toJSON(itemIds));
            String result = HttpUtil.post(url + "?open_id=" + openId + "&access_token=" + authVo.getAccessToken(), body.toJSONString());
            Object data = AjaxResult.success("success", JSON.parse(result)).get("data");
            return AjaxResult.success("success", data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult videoDetailList(List<String[]> listItem) {
        ArrayList<String> arrayList = new ArrayList<>();
        for (String[] strings : listItem) {
            String openId = strings[2];
            AuthVo authVo = redisCache.getCacheObject(openId);
            if (authVo == null) {
                return AjaxResult.error();
            }
            String url = ConstantDouYinBase.Url.BASE_URL.getUrl() + ConstantDouYinBase.Url.USER_VIDEO_DETAIL.getUrl();
            try {
                JSONObject body = new JSONObject();
                if (listItem.size() != 0) body.put("item_ids", JSONArray.toJSON(Collections.singleton(strings[0])));
                String result = HttpUtil.post(url + "?open_id=" + openId + "&access_token=" + authVo.getAccessToken(), body.toJSONString());
                arrayList.add(result);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error();
            }
        }
        return AjaxResult.success("success", arrayList);
    }

    /**
     * 获取抖音视频
     *
     * @param douyinVideoListVoList
     * @return
     */
    @Override
    public List<DouyinVideo> douyinVideoList(List<DouyinVideoListVo> douyinVideoListVoList,
                                             List<DouyinVideo> objects) {
        for (DouyinVideoListVo douyinVideoListVo : douyinVideoListVoList) {
            String openId = douyinVideoListVo.getOpenId();
            String cursor = douyinVideoListVo.getCursor();
            if (openId == null) {
                continue;
            }
            AuthVo authVo = redisCache.getCacheObject(openId);
            if (authVo == null) {
                continue;
            }
            String url = ConstantDouYinBase.Url.BASE_URL.getUrl() + ConstantDouYinBase.Url.USER_VIDEO_LIST.getUrl();
            Map<String, Object> param = new HashMap<>();
            param.put("open_id", authVo.getOpenId());
            param.put("cursor", cursor);
            param.put("access_token", authVo.getAccessToken());
//            if (last != 0 && index == douyinVideoListVoList.size()) param.put("count", last + total);
//            else param.put("count", total);
            param.put("count", 20);
            try {
                Stack<Object> objectStack = new Stack<>();
                Object data = null;
                if (objectStack.empty()) {
                    data = ajaxUtils.doGetWithParams(url, param).get("data");
                    objectStack.push(data);
                } else {
                    data = objectStack.pop();
                }
                Map map = JSON.parseObject(data.toString(), Map.class);
                Map mapResult = ((Map) map.get("data"));
                List list = ((List) ((Map) map.get("data")).get("list"));
                //objectStack.push(data);
                if (list != null) {
                    // 封装数据
                    for (Object o : list) {
                        Map listMap = (Map) o;
                        DouyinVideo douyinVideo = new DouyinVideo();
                        douyinVideo
                                .setCover(listMap.get("cover").toString())
                                .setIsReviewed(listMap.get("is_reviewed").toString())
                                .setVideoCreateTime(listMap.get("create_time").toString())
                                .setItemId(listMap.get("item_id").toString())
                                .setShareUrl(listMap.get("share_url").toString())
                                .setTitle(listMap.get("title").toString())
                                .setVideoStatus(listMap.get("video_status").toString())
                                .setIsTop(listMap.get("is_top").toString())
                                .setStatistics(JSON.toJSONString(listMap.get("statistics")))
                                .setCreateTime(new Date())
                                .setOpenId(openId)
                                .setUserId(douyinVideoListVo.getUserId())
                                .setAvatar(douyinVideoListVo.getAvatar())
                                .setNickname(douyinVideoListVo.getNickname())
                                .setUpdateTime(new Date());
                        Map statistics = JSON.parseObject(listMap.get("statistics").toString(), Map.class);
                        douyinVideo
                                .setDiggCount(statistics.get("digg_count").toString())
                                .setDownloadCount(statistics.get("download_count").toString())
                                .setForwardCount(statistics.get("forward_count").toString())
                                .setPlayCount(statistics.get("play_count").toString())
                                .setShareCount(statistics.get("share_count").toString())
                                .setCommentCount(statistics.get("comment_count").toString());
                        objects.add(douyinVideo);
                    }
                }
                if ((Boolean) mapResult.get("has_more")) {
                    douyinVideoListVo.setCursor(mapResult.get("cursor").toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<DouyinVideoListVo> videoListVos = douyinVideoListVoList.stream().filter(item -> !"0".equalsIgnoreCase(item.getCursor())).collect(Collectors.toList());
        if (videoListVos.size() > 0) {
            if (objects.size() >= 500) {
                System.out.println(objects);
                douyinVideoService.batchAddVideo(objects);
                objects.clear();
                this.douyinVideoList(videoListVos, objects);
            } else {
                this.douyinVideoList(videoListVos, objects);
            }
        }
        return objects;
    }
}
